package com.zhkj.txg.module.home.ui

import android.app.Activity
import android.content.Intent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.SPUtil
import com.zhkj.txg.R
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.home.adapter.CateProductAdapter
import com.zhkj.txg.module.home.adapter.SearchHistoryAdapter
import com.zhkj.txg.module.home.entity.ShopInfo
import com.zhkj.txg.module.home.popup.ConfirmDeletePopupWindow
import com.zhkj.txg.module.home.vm.SearchViewModel
import com.zhkj.txg.module.product.popup.ProductSharePopupWindow
import com.zhkj.txg.module.product.ui.ProductShareActivity
import com.zhkj.txg.module.product.ui.ShareFriendActivity
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.ShareUtils
import com.zhkj.txg.utils.TextWatcherWrapper
import kotlinx.android.synthetic.main.activity_search.*
import razerdp.util.KeyboardUtils
import java.lang.Exception

class SearchActivity : ViewModelActivity<SearchViewModel>() {

    companion object {
        private val CAT_ID = "id"
        private val SHOP_ID = "shopId"
        private val TYPE = "type"
        private val SHOP_CAT_ID = "shopCatId"

        fun homeOpen(activity: Activity, catId: Long) {
            val intent = Intent(activity, SearchActivity::class.java).putExtra(CAT_ID, catId)
            activity.startActivity(intent)
        }

        fun topOpen(activity: Activity) {
            val intent = Intent(activity, SearchActivity::class.java).putExtra(TYPE, 2)
            activity.startActivity(intent)
        }

        fun marketOpen(activity: Activity, catId: Long) {
            val intent = Intent(activity, SearchActivity::class.java).putExtra(TYPE, 1).putExtra(CAT_ID, catId)
            activity.startActivity(intent)
        }

        fun shopOpen(activity: Activity, shopId: Long) {
            val intent = Intent(activity, SearchActivity::class.java).putExtra(SHOP_ID, shopId)
            activity.startActivity(intent)
        }

        fun mallOpen(activity: Activity, catId: Long) {
            val intent = Intent(activity, SearchActivity::class.java).putExtra(CAT_ID, catId)
            activity.startActivity(intent)
        }
    }

    override fun setViewModel(): SearchViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleSearch
    override val layoutResId: Int = R.layout.activity_search

    private val historyAdapter = SearchHistoryAdapter().apply {
        setOnItemClickListener { _, _, position ->
            val searchKey = data[position].searchKey
            etSearch.setText(searchKey)
            etSearch.setSelection(searchKey.length)
            if (KeyboardUtils.isOpen()) KeyboardUtils.close(etSearch)
//            viewModel.searchProduct(searchKey)

            ProductListActivity.searchOpen(
                this@SearchActivity, searchKey, searchKey,
                CustomApplication.getShopId()
            )
        }
    }
    private val searchAdapter = CateProductAdapter().apply {
        loadMoreModule?.setOnLoadMoreListener {
            viewModel.searchProduct(etSearch.text.toString())
        }
        setOnItemChildClickListener { _, view, position ->
            val product = data[position]
            when (view.id) {
                // 打开店铺
//                R.id.tvCateProductShopName ->
//                    if (product.shopId > 0) ShopActivity.open(
//                        this@SearchActivity,
//                        product.shopName,
//                        product.shopId
//                    )
//                // 发圈素材
//                R.id.tvCateProductTagMatter -> ShareFriendActivity.open(
//                    this@SearchActivity,
//                    product.shareContent ?: "", product.shareImages?.toTypedArray() ?: emptyArray()
//                )
//                // 分享赚钱
//                R.id.tvCateProductTagShareEarn -> {
//                    with(sharePopupWindow) {
//                        setShareEarn(if (product.shareEarn.isNullOrEmpty()) "0.0" else product.shareEarn)
//                        productName = product.goodsName
//                        productPrice = product.price
//                        productImage = mutableListOf(product.image)
//                        goodsId = product.id.toLong()
//                        shareUrl = product.shareUrl
//                        showPopupWindow()
//                    }
//                }
            }
        }
    }

    private val deletePopupWindow: ConfirmDeletePopupWindow by lazy {
        ConfirmDeletePopupWindow(this) {
            viewModel.cleanSearchKey()
        }
    }
    private val sharePopupWindow: ProductSharePopupWindow by lazy {
        ProductSharePopupWindow(this) { type ->
            when (type) {
                2 -> {
                    if (sharePopupWindow.productImage.isNotEmpty()) ProductShareActivity.open(
                        this, sharePopupWindow.goodsId,
                        sharePopupWindow.productImage.toTypedArray(),
                        sharePopupWindow.productName,
                        sharePopupWindow.productPrice
                    ) else toast(getString(R.string.empty_gallery))
                }
                1 -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl
                )
                else -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl,
                    true
                )
            }
        }
    }
    private var refresh = false

    override fun initUI() {
//        val shopInfo1 = SPUtil.getInstance().getString(AccountManager.SHOP_INFO)
//        val shopInfo2 = try {
//            val gson = Gson()
//            gson.fromJson<ShopInfo>(shopInfo1, ShopInfo::class.java)
//        } catch (e: Exception) {
//            null
//        }
//        shopId = shopInfo2?.id!!.toInt()
        // 清除历史记录
        ivSearchClear.setOnClickListener {
            if (KeyboardUtils.isOpen()) KeyboardUtils.close(etSearch)
            deletePopupWindow.showPopupWindow()
        }
        with(rvHistory) {
            layoutManager = LinearLayoutManager(this@SearchActivity, LinearLayoutManager.HORIZONTAL, false)
            adapter = historyAdapter
        }
        with(rvSearch) {
            layoutManager = LinearLayoutManager(this@SearchActivity)
            adapter = searchAdapter
        }
        // 设置空布局
        searchAdapter.setEmptyView(layoutInflater.inflate(R.layout.layout_empty_data, null).apply {
            with(findViewById<TextView>(R.id.tvEmpty)) {
                text = getString(R.string.search_empty_hint)
                val drawable = ContextCompat.getDrawable(context, R.drawable.ic_search_empty)
                drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
                setCompoundDrawablesRelative(null, drawable, null, null)
            }
        })
        // 搜索按钮
        tvSearch.setOnClickListener {
            if (KeyboardUtils.isOpen()) KeyboardUtils.close(etSearch)
            if (!etSearch.text.isNullOrEmpty()) {
//                viewModel.searchProduct(etSearch.text.toString(), true)
                ProductListActivity.searchOpen(
                    this, etSearch.text.toString(),
                    etSearch.text.toString(),
                    CustomApplication.getShopId()
                )
                refresh = true
            }
        }
        // 搜索框搜索按钮
        etSearch.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                tvSearch.performClick()
                true
            } else false
        }
        // 当关键字为空时，隐藏列表页
        etSearch.addTextChangedListener(TextWatcherWrapper {
            if (it.isNullOrEmpty()) {
                viewHistory.visibility = View.VISIBLE
                refreshSearch.visibility = View.GONE
                if (refresh) {
                    viewModel.getSearchKey()
                    refresh = false
                }
            }
        })
        refreshSearch.setOnRefreshListener { viewModel.searchProduct(etSearch.text.toString(), true) }
    }

    override fun initViewModel() {
        // 数据保存
        viewModel.catId = intent.getLongExtra(CAT_ID, 0)
        viewModel.shopCatId = intent.getLongExtra(SHOP_CAT_ID, 0)
        viewModel.shopId = intent.getLongExtra(SHOP_ID, 0)
        viewModel.type = intent.getIntExtra(TYPE, 0)
        // 商品列表数据观察者
        viewModel.productListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // UI设置
                    viewHistory.visibility = View.GONE
                    refreshSearch.visibility = View.VISIBLE
                    // 判断加载状态
                    if (!it.loadMore) refreshSearch.finishRefresh()
                    else if (it.hasMore) searchAdapter.loadMoreModule?.loadMoreComplete()
                    else searchAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) searchAdapter.addData(it.data)
                    else searchAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) searchAdapter.loadMoreModule?.loadMoreFail()
                    else refreshSearch.finishRefresh(false)
                }
            }
        })
        // 搜索记录数据观察者
        viewModel.historyLiveData.observe(this, Observer {
            historyAdapter.setNewData(it)
        })
        viewModel.shareInfoLiveData.observe(this, Observer { response ->
            // 打开发圈素材页面
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                ShareFriendActivity.open(this, it.shareContent ?: "", it.shareImages.toTypedArray())
            }
        })
    }

    override fun initData() {
        viewModel.shopId = CustomApplication.getShopId().toLong()
        viewModel.getSearchKey()
    }
}